<template>
	<w-container class="draw" :loading="loading&&!info.id" :style="{backgroundImage:`url(${$originOssUrl}/static/draw/draw-bg.png)`}">
		<w-navbar :placeholder="false" bgColor="transparent" leftIcon="white-btn"></w-navbar>
		<view class="content_box flex flex-dir-col flex-ai-center" :style="{backgroundImage:`url(${$originOssUrl}/static/draw/${codeLen?'content-bg':'content-bg'}.png)`}">
			<view class="ljcy_box plr-15">
				<view class="font-color-black font-size-12">当前累计参与<text class="number">{{info.all_count}}</text>次</view>
			</view>
			<!-- <view @click="playVideoJump" class="video_box mt-8" :style="{backgroundImage:`url(${$originOssUrl}/static/draw/bg-video.png)`}">
				<view class="icon_play flex flex-ai-center flex-js-center">
					<image :src="$originOssUrl + '/static/draw/play.png'" style="width: 64rpx; height: 64rpx;z-index: 999;"></image>
				</view>
				<image class="fmt_image" :src="$originOssUrl + info.draw_video + '?x-oss-process=video/snapshot,t_1000,m_fast'"></image>
			</view> -->
			<image v-if="!codeLen" :src="$originOssUrl + '/static/draw/goods.png'" style="height: 530rpx;width: 414rpx; margin-top: 10rpx;" mode="aspectFit"></image>
			<image v-if="!codeLen" :src="$originOssUrl + '/static/draw/goods-name.png'" mode="heightFix" style="height: 35rpx;margin-top: 20rpx;"></image>
			<!-- <view v-if="codeLen">
				<view class="flex flex-dir-col flex-ai-center">
					<w-image src='/static/draw/my-num.png' class="mt-20 mb-12" width="116" mode='widthFix'></w-image>
					<scroll-view scroll-y="true" style="height: 25vh;width: 80%;">
						<view class="flex flex-ai-center flex-js-center flex-w gap-12">
							<view v-for="item in info.codeList" :key="item.draw_sn" :class="[info.winning_time*1000<=nowTimestamp?'br-24':'br-32',info.winning_time*1000<=nowTimestamp || item.status==1?'noActive':'active']" class="number_box active flex flex-dir-col flex-ai-center flex-js-center">
								<view>{{item.draw_sn}}</view>
								<view v-if="info.winning_time*1000<=nowTimestamp">
									<text v-if="item.status == 1">已中签</text>
									<text v-else-if="item.status == 0">未中签</text>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view> -->
			<view class="code-list plr-40" v-if="codeLen">
				<view class="code" :class="{isUncheck:info.winning_time*1000<=nowTimestamp&&item.status==0}"
					v-for="item in info.codeList" :key="item.draw_sn">
					<w-image class="tag" v-if="info.winning_time*1000<=nowTimestamp&&item.status==1"
						src='/static/draw/check.png' width="20" mode="widthFix"></w-image>
					<w-image class="tag" v-if="info.winning_time*1000<=nowTimestamp&&item.status==0"
						src='/static/draw/uncheck.png' width="20" mode="widthFix"></w-image>
					<view class="str" v-for="(str,index) in item.draw_sn" :key="str+index">
						{{str}}
					</view>
				</view>
			</view>
		</view>
		<view class="flex flex-dir-col flex-ai-center">
			<!-- <u-notice-bar  :icon='null' fontSize='20rpx' color='#fff' style="width: 280rpx;" bgColor='unset' :text="record" direction='column'></u-notice-bar> -->
			<view class="font-color-textPrimary font-size-16 mb-12" v-if="startStatus==0&&codeLen != info.get_draw_max">抽签倒计时</view>
			<view class="font-color-textPrimary font-size-16 mb-12" v-else-if="startStatus==1&&codeLen != info.get_draw_max">抽签结束倒计时</view>			
			<view class="font-color-textPrimary font-size-16 mb-12" v-else-if="(startStatus==2||codeLen==info.get_draw_max)&&countDown>0">开奖倒计时</view>
			<view class="font-color-textPrimary font-size-16 mb-12" v-else>开奖时间</view>
			<u-count-down v-if="countDown > 0" :time="countDown" format="DD:HH:mm:ss" autoStart millisecond @finish="finish" @change="onChanges">
				<view class="time flex flex-ai-center font-color-price">
					<view v-if="timeData.days" class="time__item">{{ timeData.days }}</view>
					<view v-if="timeData.days" class="font-color-white font-size-14 mlr-4">天</view>
					<view class="time__item"> {{ timeData.hours>=10?timeData.hours:'0'+timeData.hours}} </view>
					<view class="font-color-textPrimary font-size-14 mlr-4">小时</view>
					<view class="time__item">{{ timeData.minutes>=10?timeData.minutes:'0' + timeData.minutes }}</view>
					<view class="font-color-textPrimary font-size-14 mlr-4">分</view>
					<view class="time__item">{{ timeData.seconds>=10?timeData.seconds:'0' + timeData.seconds }}</view>
					<view class="font-color-textPrimary font-size-14 mlr-4">秒</view>
				</view>
			</u-count-down>
			<view class="font-size-20 font-color-textPrimary" v-else>{{info.winning_time|formatDateStr}}</view>	
			<u-gap height="20"></u-gap>
			<!-- <view class="font-color-white">{{startStatus}}</view> -->
			<w-image v-if="codeLen&&info.winning_time*1000>nowTimestamp&&startStatus==2" class="mt-12"
				src='/static/draw/awiat-open.png' @click='toInvite' width="235" mode="widthFix"></w-image>
			<w-image v-if="!codeLen&&info.winning_time*1000<=nowTimestamp&&startStatus==2" class="mt-12"
				src='/static/draw/has-open.png' @click='toInvite' width="235" mode="widthFix"></w-image>
			<w-image v-if="codeLen&&info.winning_time*1000<=nowTimestamp&&startStatus==2&&hasCheck" class="mt-12"
				src='/static/draw/is-check.png' @click='toInvite' width="235" mode="widthFix"></w-image>
			<w-image v-if="codeLen&&info.winning_time*1000<=nowTimestamp&&startStatus==2&&!hasCheck" class="mt-12"
				src='/static/draw/un-check.png' @click='toInvite' width="235" mode="widthFix"></w-image>
			<w-image v-if="codeLen == info.get_draw_max&&info.winning_time*1000>nowTimestamp" class="mt-12"
				src='/static/draw/awiat-open.png' @click='toInvite' width="235" mode="widthFix"></w-image>
			<w-image v-if="startStatus==0" class="mt-12" src='/static/draw/un-start.png' width="235"
				mode="widthFix"></w-image>
			<w-image v-if="startStatus==1&&info.remaining>0&&!codeLen" @click.native='draw' class="mt-12"
				src='/static/draw/sign.png' width="235" mode="widthFix"></w-image>
			<w-image v-if="startStatus==1&&info.remaining>0&&codeLen" @click.native='draw' class="mt-12"
				src='/static/draw/sign1.png' width="235" mode="widthFix"></w-image>
			<w-image v-if="startStatus==1&&info.remaining_invited && info.how_people_get_draw > 1 && info.remaining == 0 && codeLen<info.get_draw_max &&codeLen" @click.native='toInvite'
				class="mt-12" src='/static/draw/invite.png' width="235" mode="widthFix"></w-image>
			<w-image v-if="startStatus==1&&info.remaining_invited && info.how_people_get_draw == 1 && info.remaining == 0 && codeLen<info.get_draw_max &&codeLen" @click.native='toInvite'
				class="mt-12" src='/static/draw/invite-1.png' width="235" mode="widthFix"></w-image>
			<view v-if="startStatus==1&&info.remaining_invited&&codeLen" class="again_box">（<text>再</text>邀请{{info.remaining_invited}}位用户可额外获得一个签号）</view>
		</view>
		<view class="right_btn_box">
			<w-image src='/static/draw/record.png' @click.native='toRecord' class="btn2" width="28" mode="widthFix"></w-image>
			<w-image src='/static/draw/my_btn-code.png' @click.native='changefrequencysHow' class="mt-10" width="28" mode="widthFix"></w-image>
			<w-image src='/static/draw/rule.png' @click.native='toRule' class="mt-10" width="28" mode="widthFix"></w-image>
		</view>
		<u-popup :show='showNum' mode='center' bgColor='transparent' round='32rpx'>
			<view class="pt-20 num-popup pb-16 flex flex-dir-col flex-js-sb flex-ai-center"> 
				<view class="flex flex-dir-col flex-ai-center">
					<image :src="$originOssUrl + '/static/draw/popup_hua.png'" style="width: 382rpx;height: 382rpx;"></image>
				</view>
				<view class="bg-color-item br-18 flex flex-dir-col flex-ai-center pb-12" style="width: 600rpx;box-sizing: border-box;margin-top: -180rpx;">
					<view class="font-size-16" style="color: #999;margin-top: 100rpx;">恭喜获得签号</view>
					<view class="font-w-bold font-color-textPrimary mt-16">{{num}}</view>
					<u-line margin="32rpx 0"></u-line>
					<view @click="showNum = false" class="font-color-textPrimary">我知道了</view>
				</view>
			</view>
		</u-popup> 
		<u-popup :show='invitShow' @close="invitShow = false" @open="invitShow = true" closeOnClickOverlay mode='center' bgColor='transparent' round='32rpx'>
			<view class="flex flex-dir-col flex-ai-center">
				<image :src="$originOssUrl + '/static/draw/popup_hua.png'" style="width: 382rpx;height: 382rpx;"></image>	
				<view class="bg-color-white br-18 flex flex-dir-col flex-ai-center pb-16" style="width: 600rpx;margin-top: -180rpx;">
					<view class="font-size-16" style="color: #666;margin-top: 100rpx;">邀请二维码</view>
					<w-qrcode :content="invitaion_code" bgColor="unset"  :size="170" class="img mtb-12" @change='setQrcodeImg'></w-qrcode>
					<u-line margin="32rpx 0"></u-line>
					<!-- <view @click="draw_start" class="mb-16 font-color-black">保存二维码</view> -->
					<view class="flex flex-ai-center flex-js-sa" style="width: 70%;">
						<w-button @click="copyInviteUrl" pain size="ss">复制链接</w-button>
						<w-button @click="draw_start" size="ss">保存二维码</w-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup :show='frequencysHow' @close="frequencysHow = false" @open="frequencysHow = true" closeOnClickOverlay mode='center' bgColor='#fff' round='16rpx'>
			<view class="flex flex-dir-col flex-ai-center plr-16 ptb-24" style="width: 600rpx;">
				<view class="font-color-black font-size-16 font-w-bold font-size-14" >我的抽签次数: {{info.remaining}}</view>
				<view class="mt-8" style="color: #666;">
					<text>已邀请</text>
					<text class="font-color-textPrimary">{{ all_invited_people }}</text>
					<text>位好友预约</text>
				</view>
				<view class="flex flex-ai-center mt-18 mb-4" style="width: 100%;">
					<view style="width: 50%;color: #666;" class="text-center ">手机号</view>
					<view style="width: 50%;color: #666;" class="text-center ">邀请状态</view>
				</view>
				<scroll-view scroll-y="true" style="max-height: 60vh;">
					<view v-for="item in frequencyList" :key="item.id" class="flex flex-ai-center mt-8" style="width: 100%;">
						<view style="width: 50%;color: #222;" class="text-center ">{{item.mobile}}</view>
						<view style="width: 50%;color: #26B657;" class="text-center ">成功</view>
					</view>
				</scroll-view>
				<w-loading v-if="!frequencyList.length" type="empty" empty-type="search"></w-loading>
			</view>
		</u-popup>
		<view style="position: fixed;z-index: -1000;">
			<w-canvas :isDraw="isDraw" :canvasData="canvasData" :imageSize="{width: 343, height: 526}" @generateImageSuccessful="drawAccomplish"></w-canvas>
		</view>
	</w-container>
</template>

<script>
	import {
		getDraw,
		draw,
		drawRecord,
		invited_record
	} from '@/api/draw/index.js'
	import {
		mapState,
		mapActions
	} from 'vuex'
	import dayjs from 'dayjs'
	export default {
		data() {
			return {
				loading: true,
				id: null,
				showNum: false,
				info: {
					codeList: []
				},
				num: '',
				record: [],
				timeData:{},
				invitShow:false,
				isDraw:false,
				canvasData:[],
				showPoster: false,
				posterImg:'',
				frequencysHow:false,
				frequencyList:[],
				all_invited_people:0
			}
		},
		onLoad({
			thm
		}) {
			this.id = thm;
			this.getInfo();
			this.createNowTimeTimer()
		},
		onShow() {
			if(!this.info.id) {
				this.getInfo();
				this.createNowTimeTimer()
			}
		},
		onPullDownRefresh() {
			this.getInfo()
		},
		filters: {
			formatDateStr(v) {
				return dayjs(v * 1000).format('YYYY年MM月DD日HH:mm')
			}
		},
		computed: {
			...mapState('config', ['nowTimestamp']),
			// 邀请二维码
			invitaion_code() {
				let time = new Date().getTime();
				// 当前页面路径
				let curRoute=getCurrentPages()
				let fullUrl='/\#'+curRoute[curRoute.length-1].$page.fullPath
				
				let url=`${this.appConfig.h5_domain + '/#/pages/activity/draw?a=1'}&inviter_user_id=${this.userInfo.id}&t=${time}&thm=${this.id}`				
				return url
			},
			//开始状态
			startStatus() { //1为在中间，0在开始时间前，2在结束时间后
				return this.$tools.checkTimeBetween(this.nowTimestamp, this.info.reg_start_time * 1000, this.info
					.reg_end_time * 1000)
			},
			hasCheck() {  
				return this.info.codeList.map(v => v.status).includes('1')
			},
			//倒计时
			countDown() {
				if (this.startStatus == 0 && this.codeLen != this.info.get_draw_max) {
					return this.info.reg_start_time * 1000 - this.nowTimestamp
				} else if (this.startStatus == 1 && this.codeLen != this.info.get_draw_max) {
					return this.info.reg_end_time * 1000 - this.nowTimestamp
				}
				return this.info.winning_time * 1000 - this.nowTimestamp
			},
			formatStr() {
				if (this.countDown < 1000 * 60 * 60 * 24) {
					return 'HH:mm:ss'
				}
				return 'DD天HH:mm:ss'
			},
			//报名状态
			codeLen() {
				return this.info.codeList.length
			},		
			toRule() {
				uni.setStorage({
					data: this.info.content,
					key: 'draw-text',
					success() {
						uni.navigateTo({
							url: '/pages/rules/rules?type=6'
						})
					}
				})
			},
		},
		methods: {
			...mapActions('config', ['createNowTimeTimer']),
			getInfo() {
				this.loading = true;
				getDraw(this.id).then(res => {
					this.info = res.data;
					this.$forceUpdate()

				}).finally(() => {
					this.loading = false
					// this.getRecord();
					uni.stopPullDownRefresh()
				})
			},
			getRecord() {
				drawRecord(this.id).then(res => {

					this.record = res.data.map(v => {
						return v.nickname + "已中签"
					})
					// console.log(this.record)
				})
			},
			changefrequencysHow(){
				uni.navigateTo({
					url: '/pages/invitation/invitation'
				})
				// this.getFrequencyList()
			},
			getFrequencyList(){
				// uni.showLoading({
				// 	title:'查询中...'
				// })
				// invited_record(this.id).then( res => {
				// 	this.all_invited_people = res.data.all_invited_people
				// 	this.frequencyList = res.data.data
				// 	this.frequencysHow = true
				// })
			},
			draw() {
				uni.showLoading({
					title: "抽签中"
				})
				let form = {
					id:this.id			
				}
				if(uni.getStorageSync('inviter_user_id')) form.inviter_user_id = uni.getStorageSync('inviter_user_id')
				draw(form).then(res => {
					this.num = res.data;
					uni.removeStorageSync('inviter_user_id')
					this.showNum = true;
				}).finally(() => {
					this.getInfo();
				})
			},
			toInvite() {
				uni.navigateTo({
					url: '/pages/invitation/invitation'
				})
				// this.invitShow = true
			},
			toRecord() {
				uni.navigateTo({
					url: '/pages/activity/record?id=' + this.id
				})
			},
			finish(){
				this.$emit('finish')
			},
			onChanges(e) {
				this.timeData = e
			},
			playVideoJump(){
				if(!this.info.draw_video) {
					uni.showToast({
						title:'暂无视频',
						icon:'none'
					})
					return
				}
				uni.navigateTo({
					url:`/pages/activity/playVideo?url=` + JSON.stringify(this.info.draw_video)
				})
			},
			//设置二维码本地路径
			setQrcodeImg(v){
				this.localQrcodePath=v;
			},
			// 复制邀请码
			copyInviteUrl() {
				this.invitShow = false
				this.$tools.copyText(this.invitaion_code)
			},
			// 绘制
			draw_start(code){
				this.invitShow = false
				if(this.posterImg){
					this.drawAccomplish(this.posterImg)
					return
				}
				uni.showLoading({ title:'绘制中...' })
				this.isDraw = true;
				console.log(this.appConfig);
				let bgImg = this.$originOssUrl + this.appConfig.share_bac_iamge;
				let codeImg = this.invitaion_code;
				this.canvasData = [
					{ type: 'rect', attr: { color: '#fff', x: 0, y: 0, width: 343, height: 526 } },
					{ type: 'image', attr: { image: bgImg, x: 0, y: 0, width: 343, height: 526 } },
					{ type: 'image', attr: { image: this.localQrcodePath, x: 245, y: 400, width: 80, height: 80 } },
				]
			},
			
			//绘制完成
			drawAccomplish(url) {
				if(!this.posterImg) uni.hideLoading();
				this.posterImg = url;
				this.showPoster = true;
				
				//#ifdef H5
					let ua = navigator.userAgent.toLowerCase();
					if (ua.indexOf('micromessenger') != -1){
						uni.$u.toast('长按保存到系统相册')
						return
					}
					let a = document.createElement('a')
					a.setAttribute('download', "")
					a.setAttribute('href', url)
					document.body.appendChild(a);
					a.style.display = 'none'
					a.click()
					document.body.removeChild(a)
					uni.$u.toast('图片已保存到系统相册')
				//#endif
				//#ifndef H5
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success() {
							uni.$u.toast('图片已保存到系统相册')
						},
						fail(err){
							console.log(err)
						}
					})
				//#endif
			}
		}
	}
</script>

<style lang="scss">
	.draw {
		// @include ossBg('/static/draw/draw-bg.png');
		background-size: 750rpx auto;
		background-repeat: no-repeat;
		background-color: #FEDDC9;
		.content_box {
			width: 579rpx;
			height: 1122rpx;
			background-size: 100% 100%;
			margin: 0rpx auto 0;
			background-repeat: no-repeat;
			.ljcy_box {
				margin-top: 56%;
				// min-width: 257.57rpx;
				height: 51.85rpx;
				background-size: 100% 100%;
				background-repeat: no-repeat;
				text-align: center;
				line-height: 51.85rpx;
				@extend .plr-10;
				.number {
					margin: 0 4rpx;
					color: #FFA454;
				}
			}
			.video_box {
				width: 492rpx;
				height: 276rpx;
				background-size: 100% 100%;
				background-repeat: no-repeat;
				padding: 22rpx 40rpx;
				position: relative;
				.icon_play {
					width: 100%;
					height: 100%;
					z-index: 99;
				}
				.fmt_image {				
					width: calc(100% - 80rpx);
					height: calc(100% - 44rpx);
					position: absolute;
					left: 40rpx;
					top: 22rpx;
					margin: auto;
					z-index: 1;
				}
			}
			.code-list {
				width: 100%;
			
				@extend .flex, .flex-js-sa;
			
			
				.code {
					background: url($IMG_URL + '/static/draw/num-bg.png');
					width: 176rpx;
					height: 560rpx;
					background-size: 100% 100%;
					@extend .flex, .flex-dir-col, .flex-ai-center, .flex-js-center;
					color: #222;
					font-weight: bold;
					position: relative;
					font-size: 48rpx;
					line-height: 43rpx;
			
					.tag {
						position: absolute;
						top: 430rpx;
						// left: ;
					}
			
					// font-size: 26px;
				}
			
				.isUncheck {
					background: url($IMG_URL + '/static/draw/num-bg-1.png');
					background-size: 176rpx 560rpx;
					color: #8C8C8C;
				}
			
			}
			.number_box {
				padding: 8rpx 10rpx;
				font-size: 28rpx;
			}
			.active {
				border-radius: 40rpx;
				background-color: #FFE0CE;
				color: #DD544B;
			}
			.noActive {
				border-radius: 24rpx;
			}
		}
		.time {		
		    &__item {
		         width: 48rpx;
		         height: 48rpx;
		         background: #C18200;
		         border-radius: 8rpx 8rpx 8rpx 8rpx;
		         opacity: 1;
		         border: 1rpx solid #C18200;
				 line-height: 48rpx;
				 text-align: center;
				 color: #fff;
		     }
		}
		
		.right_btn_box {
			position: fixed;
			right: 0;
			top: 100rpx;
		}
		.again_box {
			width: 100%;
			height: 80rpx;
			background: linear-gradient( 90deg, rgba(253,173,54,0) 0%, #FDAD36 49%, rgba(253,173,54,0) 100%);
			background-size: 100% 100%;
			background-repeat: no-repeat;
			text-align: center;
			line-height: 80rpx;
			font-size: 28rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			margin-top: 30rpx;
		}
	}
</style>